<template>
  <view class="page-container w-[750rpx] bg-gray-50 min-h-screen mx-auto">
    <backView />
    <!-- 页面标题 -->
    <view class="page-header bg-gradient-to-r from-purple-500 to-purple-600 text-white p-[30rpx] shadow-md relative">
      <text class="text-[32rpx] font-bold text-center block">社会经济学信息</text>
    </view>

    <!-- 加载状态 -->
    <view v-if="loading" class="loading-container flex justify-center items-center py-[100rpx]">
      <view class="flex flex-col items-center">
        <view class="animate-spin rounded-full h-[80rpx] w-[80rpx] border-t-2 border-b-2 border-purple-500 mb-[20rpx]"></view>
        <text class="text-[32rpx] text-gray-500">加载中...</text>
      </view>
    </view>

    <!-- 空状态 -->
    <view v-else-if="records.length === 0" class="empty-container flex flex-col justify-center items-center py-[100rpx] px-[40rpx]">
      <view class="bg-gray-100 rounded-full p-[40rpx] mb-[32rpx]">
        <text class="text-[72rpx]">📊</text>
      </view>
      <text class="text-[32rpx] text-gray-700 font-medium mb-[32rpx] text-center">暂无社会经济学信息</text>
      <nut-button type="primary" class="bg-gradient-to-r from-purple-500 to-purple-600 border-0 rounded-[12rpx] shadow px-[60rpx]" @click="goAdd"> 添加第一条 </nut-button>
    </view>

    <!-- 记录列表 -->
    <view v-else class="px-[24rpx] pb-[60rpx] relative">
      <Items v-for="(record, index) in records" :key="record.id" :record="record" @edit="goEdit" @delete="deleteRecord" />
    </view>

    <!-- 加载更多 -->
    <view v-if="hasMore" class="load-more-container flex justify-center py-[32rpx]">
      <view v-if="loadingMore" class="flex items-center">
        <view class="animate-spin rounded-full h-[40rpx] w-[40rpx] border-t-2 border-b-2 border-purple-500 mr-[16rpx]"></view>
        <text class="text-[28rpx] text-gray-500">加载中...</text>
      </view>
      <view v-else class="text-[28rpx] text-gray-400">上拉加载更多</view>
    </view>
    
    <!-- 没有更多数据 -->
    <view v-else-if="records.length > 0" class="no-more-container flex justify-center py-[32rpx]">
      <text class="text-[28rpx] text-gray-400">没有更多数据了</text>
    </view>

    <!-- 悬浮添加按钮 -->
    <view class="fab-container fixed bottom-[48rpx] right-[48rpx] z-50">
      <nut-button
        type="success"
        class="!w-[90rpx] !h-[90rpx] !min-w-[90rpx] !min-h-[90rpx] rounded-full bg-gradient-to-br from-purple-500 to-purple-600 shadow-lg transition-transform duration-300 hover:scale-110"
        @click="goAdd"
      >
        <template #icon>
          <IconFont name="uploader" size="30" class="text-white" />
        </template>
      </nut-button>
    </view>
  </view>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed } from "vue";
import Taro from "@tarojs/taro";
import { request } from "@/service/request";
import { IconFont } from "@nutui/icons-vue-taro";
import { localStg } from "@/utils";
import Items from "./items.vue";
import backView from "@/components/backView.vue";

const loading = ref(false);
const loadingMore = ref(false);
const records = ref<any[]>([]);
const total = ref(0);
const currentPage = ref(1);
const pageSize = ref(10);

// 计算是否还有更多数据
const hasMore = computed(() => {
  return records.value.length < total.value;
});

const searchForm = reactive({
  name: "",
  recordid: "",
});

onMounted(() => {
  const obj = localStg.get("demographicInfo");
  if (obj) {
    searchForm.recordid = obj.recordid;
  }
  loadRecords();
});

// 页面显示时重新加载数据
Taro.useDidShow(() => {
  console.log("页面显示，重新加载数据");
  // 重置页码并重新加载
  currentPage.value = 1;
  loadRecords();
});

// 监听页面滚动到底部
Taro.useReachBottom(() => {
  console.log("页面滚动到底部，加载更多数据");
  loadMore();
});

async function loadRecords(isLoadMore = false) {
  // 防止重复请求
  if (loading.value || (isLoadMore && loadingMore.value)) {
    return;
  }
  
  if (isLoadMore) {
    loadingMore.value = true;
  } else {
    loading.value = true;
  }
  
  try {
    const params = {
      page: currentPage.value,
      size: pageSize.value,
      ...searchForm,
    };

    const result = await request.get<any>("/health_records/health_social/healthSocialInfo/list", params, {
      useErrMsg: true,
    });

    if (result.success) {
      if (isLoadMore) {
        // 追加数据
        records.value = [...records.value, ...(result.success.records || [])];
      } else {
        // 替换数据
        records.value = result.success.records || [];
      }
      total.value = result.success.total || 0;
    }
  } catch (error) {
    console.error("加载数据失败:", error);
    Taro.showToast({ title: "加载数据失败", icon: "error" });
  } finally {
    if (isLoadMore) {
      loadingMore.value = false;
    } else {
      loading.value = false;
    }
  }
}

async function loadMore() {
  if (!hasMore.value || loadingMore.value) {
    return;
  }
  
  currentPage.value += 1;
  await loadRecords(true);
}

function goAdd() {
  Taro.navigateTo({
    url: "./add",
    success: () => {
      console.log("跳转到添加页面");
    },
    fail: (error) => {
      console.error("跳转失败:", error);
      Taro.showToast({ title: "跳转失败", icon: "error" });
    }
  });
}

function goEdit(id: string) {
  Taro.navigateTo({
    url: `./edit?id=${id}`,
    success: () => {
      console.log("跳转到编辑页面，ID:", id);
    },
    fail: (error) => {
      console.error("跳转失败:", error);
      Taro.showToast({ title: "跳转失败", icon: "error" });
    }
  });
}

async function deleteRecord(id: string) {
  try {
    const result = await Taro.showModal({
      title: "确认删除",
      content: "确定要删除这条记录吗？",
      confirmText: "删除",
      cancelText: "取消",
    });

    if (result.confirm) {
      await request.delete(
        `/health_records/health_social/healthSocialInfo/delete?id=${id}`,
        {},
        {
          useErrMsg: true,
        }
      );

      Taro.showToast({ title: "删除成功", icon: "success" });
      loadRecords();
    }
  } catch (error) {
    console.error("删除失败:", error);
    Taro.showToast({ title: "删除失败", icon: "error" });
  }
}
</script>

<style>
/* 加载动画 */
@keyframes spin {
  from {
    transform: rotate(0deg);
  }
  to {
    transform: rotate(360deg);
  }
}

.animate-spin {
  animation: spin 1s linear infinite;
}

/* 卡片悬停效果 */
.content-card {
  transition: all 0.3s ease;
}
</style>